package com.lgj.rocketmq.product;

import com.alibaba.fastjson.JSONObject;
import com.lgj.rocketmq.message.RocketMessage;
import com.lgj.rocketmq.product.callback.DefaultSendCallBack;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.bouncycastle.pqc.crypto.newhope.NHSecretKeyProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: guangjie.liao
 * @Date: 2023/8/28 22:122
 * @Description: 事务消息生产者
 */
@Slf4j
@Component
public class RocketMQProducer {

    @Autowired
    private TransactionMQProducer transactionMQProducer;

    /**
     * 事务消息发送
     * @param Message RocketMessage
     * @return TransactionSendResult
     * @author guangjie.liao
     * @since 2023/9/19 21:40
     */
    public TransactionSendResult sendTransactionMessage(Message message){
        TransactionSendResult transactionSendResult = null;
        try {
            transactionSendResult = transactionMQProducer.sendMessageInTransaction(message,null);
        } catch (Exception e) {
            log.error("消息发送失败，消息topic:{},消息内容：{}，\n 错误信息:{}", message.getTopic(),
                    JSONObject.toJSONString(JSONObject.parse(message.getBody())),e.getMessage());
        }
        return transactionSendResult;
    }

    /**
     * 同步发送
     * @param Message RocketMessage
     * @return SendResult
     * @author guangjie.liao
     * @since 2023/9/19 21:40
     */
    public SendResult sendSync(Message message){
        SendResult result = null;
        try {
            result = transactionMQProducer.send(message);
        } catch (Exception e) {
            log.error("消息发送失败，消息topic:{},消息内容：{}，\n 错误信息:{}", message.getTopic(),
                    JSONObject.toJSONString(JSONObject.parse(message.getBody())),e.getMessage());
        }
        return result;
    }

    /**
     * 异步发送
     * @param Message message
     * @return SendResult
     * @author guangjie.liao
     * @since 2023/9/19 22:56
     */
    public void sendAsync(Message message){
        try {
            transactionMQProducer.send(message,new DefaultSendCallBack());
        } catch (Exception e) {
            log.error("消息发送失败，消息topic:{},消息内容：{}，\n 错误信息:{}", message.getTopic(),
                    JSONObject.toJSONString(JSONObject.parse(message.getBody())),e.getMessage());
        }
    }
}
